package com.me.components {
	import com.me.FileLoader;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.geom.Point;
	import flash.system.ApplicationDomain;
	import flash.system.IME;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.utils.getDefinitionByName;
	
	import spark.core.SpriteVisualElement;

	/**
	 *
	 * @author yw
	 *
	 * @Date 2011-9-16 下午03:48:48
	 */
	public class PortalAvatar extends MapResource {
		protected var _spName:TextField = new TextField();
		protected var _dragHandler:Function;
		protected var _stopDragHandler:Function;

		public function PortalAvatar(file:File, handler:Function, dragHandler:Function = null, stopDragHandler:Function = null) {
			super();
			mouseChildren = mouseEnabled = true;
			_fileName = file.name;
			_loadCompleteHandler = handler;
			_dragHandler = dragHandler;
			_stopDragHandler = stopDragHandler;
			_spName.width = 60;
			_spName.type = TextFieldType.INPUT;
			_spName.autoSize = TextFieldAutoSize.CENTER;
			_spName.background = true;
			_spName.backgroundColor = 0xff0000;
			_spName.text = "Portal";
			_spName.mouseEnabled = false;
			_spName.addEventListener(FocusEvent.FOCUS_IN, function(e:FocusEvent):void {
				IME.enabled = true;
			});
			FileLoader.getInstance().loadFile(file, fileLoaded);
			
			addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
		}

		private function fileLoaded(content:Object):void {
			try {
				var obj:Object = FileLoader.getInstance().getClassByName("Portal");
				var portal:MovieClip = (new obj()) as MovieClip;
				portal.addEventListener(Event.ADDED_TO_STAGE, function(e:Event):void {
					(e.currentTarget as MovieClip).gotoAndPlay(1);
					portal.x = -portal.width >> 1
					portal.y = -portal.height;
					_spName.x = -_spName.textWidth >> 1;
					_spName.y = portal.y - _spName.textHeight - 10;
				});
				portal.mouseEnabled = portal.mouseChildren = true;
				addChild(portal);
				addChild(_spName);
				
				_loadCompleteHandler(this);
			} catch (e:Error) {

			}
		}

		private function onMouseDownHandler(e:MouseEvent):void {
			if (stage) {
				stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
				startDrag(false);
				if (_dragHandler != null) {
					_dragHandler();
				}
			}
		}

		private function onMouseUpHandler(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			stopDrag();
			if (_stopDragHandler != null) {
				_stopDragHandler();
			}
		}
	}
}
